package com.atguigu.gulimall.ssoserver.controller;

import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

  @Autowired
  StringRedisTemplate redisTemplate;

  @ResponseBody
  @GetMapping("/userInfo")
  public String userInfo(@RequestParam("token") String token) {
    return redisTemplate.opsForValue().get(token);
  }

  @GetMapping(value = "/login.html")
  public String loginPage(@RequestParam("redirect_url") String url, Model model) {
    model.addAttribute("url", url);
    return "login";
  }

  @PostMapping(value = "/doLogin")
  public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
      @RequestParam("url") String url, HttpServletResponse rHttpServletResponse) {
    if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
      String uuid = UUID.randomUUID().toString().replace("-", "");
      redisTemplate.opsForValue().set(uuid, username);
      Cookie cookie = new Cookie("sso_token", uuid);
      rHttpServletResponse.addCookie(cookie);
      return "redirect:" + url + "?token=" + uuid;
    }
    return "login";
  }

}
